<template>
  <div class="register-page">
    <div class="register-bg"></div>
    
    <div class="register-container">
      <div class="register-form-container">
        <div class="form-title">用户注册</div>
        
        
        
        <form @submit.prevent="register" class="register-form">
          <!-- 第一行：昵称和邮箱 -->
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">昵称:</label>
              <div class="input-wrapper">
                <input 
                  type="text" 
                  v-model="ruleForm.nickname" 
                  placeholder="请输入昵称"
                  class="form-input"
                  required
                />
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">邮箱:</label>
              <div class="input-wrapper">
                <input 
                  type="email" 
                  v-model="ruleForm.email" 
                  placeholder="请输入邮箱"
                  class="form-input"
                  required
                />
              </div>
            </div>
          </div>
          
          <!-- 第二行：年龄和密码 -->
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">年龄:</label>
              <div class="input-wrapper">
                <input 
                  type="number" 
                  v-model="ruleForm.age" 
                  placeholder="请输入年龄"
                  class="form-input"
                  min="16"
                  max="100"
                  required
                />
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">密码:</label>
              <div class="input-wrapper">
                <input 
                  type="password" 
                  v-model="ruleForm.password" 
                  placeholder="请输入密码"
                  class="form-input"
                  required
                />
              </div>
            </div>
          </div>
          
          <!-- 第三行：确认密码和省份选择 -->
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">确认密码:</label>
              <div class="input-wrapper">
                <input 
                  type="password" 
                  v-model="ruleForm.confirmPassword" 
                  placeholder="请再次输入密码"
                  class="form-input"
                  required
                />
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">省份:</label>
              <div class="input-wrapper">
                <select 
                  v-model="ruleForm.provinceCode" 
                  @change="onProvinceChange"
                  class="form-input"
                  required
                >
                  <option value="">请选择省份</option>
                  <option v-for="province in provinces" :key="province.code" :value="province.code">
                    {{ province.name }}
                  </option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 第四行：城市和区县选择 -->
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">城市:</label>
              <div class="input-wrapper">
                <select 
                  v-model="ruleForm.cityCode" 
                  @change="onCityChange"
                  class="form-input"
                  :disabled="!ruleForm.provinceCode"
                >
                  <option value="">请选择城市</option>
                  <option v-for="city in cities" :key="city.code" :value="city.code">
                    {{ city.name }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">区县:</label>
              <div class="input-wrapper">
                <select 
                  v-model="ruleForm.districtCode" 
                  class="form-input"
                  :disabled="!ruleForm.cityCode"
                >
                  <option value="">请选择区县</option>
                  <option v-for="district in districts" :key="district.code" :value="district.code">
                    {{ district.name }}
                  </option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 第五行：详细地址 -->
          <div class="form-row">
            <div class="form-group full-width">
              <label class="form-label">详细地址:</label>
              <div class="input-wrapper">
                <input 
                  type="text" 
                  v-model="ruleForm.expectedLocation" 
                  placeholder="请输入详细地址（可选）"
                  class="form-input"
                />
              </div>
            </div>
          </div>
          
                     <!-- 第六行：理想薪资范围 -->
           <div class="form-row">
             <div class="form-group">
               <label class="form-label">最低期望薪资:</label>
               <div class="input-wrapper">
                 <input 
                   type="number" 
                   v-model="ruleForm.salaryMin" 
                   placeholder="请输入最低期望薪资"
                   class="form-input"
                   min="1"
                   required
                 />
                 <span class="unit-label">k</span>
               </div>
             </div>
             
             <div class="form-group">
               <label class="form-label">最高期望薪资:</label>
               <div class="input-wrapper">
                 <input 
                   type="number" 
                   v-model="ruleForm.salaryMax" 
                   placeholder="请输入最高期望薪资"
                   class="form-input"
                   min="1"
                   required
                 />
                 <span class="unit-label">k</span>
               </div>
             </div>
           </div>
          
          <!-- 理想岗位关键词 -->
          <div class="keywords-section">
            <label class="form-label">理想岗位关键词:</label>
            <div class="keywords-grid">
              <button 
                v-for="keyword in keywords" 
                :key="keyword"
                type="button"
                :class="['keyword-btn', { 'selected': selectedKeywords.includes(keyword) }]"
                @click="toggleKeyword(keyword)"
              >
                {{ keyword }}
              </button>
            </div>
          </div>
          
          <button type="submit" class="register-btn" :disabled="isLoading">
            <span v-if="!isLoading">注册</span>
            <span v-else>注册中...</span>
          </button>
        </form>
        
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <!-- 返回登录 -->
        <div class="back-to-login">
          <span>已有账号？</span>
          <a @click="goToLogin" class="login-link">立即登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { register } from '@/api/authApi'
import request from '@/utils/request'

export default {
  name: "Register",
     data() {
     return {
       isLoadingProvinces: false,
             ruleForm: {
         nickname: '',
         email: '',
         age: '',
         password: '',
         confirmPassword: '',
         expectedLocation: '',
         salaryMin: '',
         salaryMax: '',
         provinceCode: '',
         cityCode: '',
         districtCode: '',
       },
             keywords: [
         '全栈', '后端', 'C/C++/C#', '前端',
         'Golang', 'Java', 'Javascript', 'NodeJS',
         '运维', 'Python', '测试', 'Web'
       ],
      selectedKeywords: [],
      provinces: [],
      cities: [],
      districts: [],
      isLoading: false,
      errorMessage: ''
    };
  },
     created() {
     // 组件创建完成
   },
     async mounted() {
     // 防止重复加载
     if (!this.isLoadingProvinces && this.provinces.length === 0) {
       try {
         await this.loadProvinces();
       } catch (error) {
         console.error('组件挂载时出错:', error);
       }
     }
   },
  methods: {
         async loadProvinces() {
       // 防止重复加载
       if (this.isLoadingProvinces) {
         return;
       }
       
       this.isLoadingProvinces = true;
       try {
         const response = await request.get('/api/region/provinces');
         if (response.code === 200) {
           // 过滤掉"中华人民共和国"，只保留真正的省份
           this.provinces = response.data.filter(province => 
             province.code !== '100000' && province.name !== '中华人民共和国'
           );
         } else {
           console.error('省份API返回错误:', response);
         }
       } catch (error) {
         console.error('加载省份失败:', error);
       } finally {
         this.isLoadingProvinces = false;
       }
     },
    
    async onProvinceChange() {
      this.ruleForm.cityCode = '';
      this.ruleForm.districtCode = '';
      this.cities = [];
      this.districts = [];
      
      if (this.ruleForm.provinceCode) {
        try {
          const response = await request.get(`/api/region/cities/${this.ruleForm.provinceCode}`);
          if (response.code === 200) {
            this.cities = response.data;
          }
        } catch (error) {
          console.error('加载城市失败:', error);
        }
      }
    },
    
    async onCityChange() {
      this.ruleForm.districtCode = '';
      this.districts = [];
      
      if (this.ruleForm.cityCode) {
        try {
          const response = await request.get(`/api/region/districts/${this.ruleForm.cityCode}`);
          if (response.code === 200) {
            this.districts = response.data;
          }
        } catch (error) {
          console.error('加载区县失败:', error);
        }
      }
    },
    
    toggleKeyword(keyword) {
      const index = this.selectedKeywords.indexOf(keyword);
      if (index > -1) {
        this.selectedKeywords.splice(index, 1);
      } else {
        this.selectedKeywords.push(keyword);
      }
    },
    
         goToLogin() {
       this.$router.push('/login');
     },
    
    async register() {
             // 表单验证
       if (!this.ruleForm.nickname || !this.ruleForm.email || !this.ruleForm.age || 
           !this.ruleForm.password || !this.ruleForm.confirmPassword || 
           !this.ruleForm.salaryMin || !this.ruleForm.salaryMax) {
         this.errorMessage = '请填写所有必填字段';
         return;
       }
      
             if (this.ruleForm.password !== this.ruleForm.confirmPassword) {
         this.errorMessage = '两次输入的密码不一致';
         return;
       }
       
               // 薪资范围验证
        const minSalary = parseInt(this.ruleForm.salaryMin);
        const maxSalary = parseInt(this.ruleForm.salaryMax);
        
        if (minSalary >= maxSalary) {
          this.errorMessage = '最高薪资必须大于最低薪资';
          return;
        }
      
      if (!this.ruleForm.provinceCode) {
        this.errorMessage = '请选择省份';
        return;
      }
      
      if (this.selectedKeywords.length === 0) {
        this.errorMessage = '请至少选择一个理想岗位关键词';
        return;
      }
      
      this.isLoading = true;
      this.errorMessage = '';
      
                      try {
           const registerData = {
             ...this.ruleForm,
             salaryRange: `${this.ruleForm.salaryMin}k-${this.ruleForm.salaryMax}k`,
             idealKeywords: this.selectedKeywords.join(',')
           };
         
         const response = await register(registerData);
         
         if (response.code === 200) {
           this.$message.success('注册成功，请登录');
           this.$router.push('/login');
         } else {
           this.errorMessage = response.message || response.msg || '注册失败';
         }
       } catch (error) {
         console.error('注册失败:', error);
         this.errorMessage = '注册失败，请检查网络连接';
       } finally {
                 this.isLoading = false;
       }
     }
  }
}
</script>

<style scoped>
.register-page {
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #010e50 url(@/assets/images/bg.jpg) center top no-repeat;
  background-size: 100% auto;
  color: #fff;
  position: relative;
  overflow: hidden;
}

.register-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 35, 120, 0.3);
  backdrop-filter: blur(2px);
}

.register-container {
  position: relative;
  z-index: 10;
  background: rgba(0, 35, 120, 0.8);
  border: 1px solid rgba(62, 171, 255, 0.3);
  border-radius: 15px;
  padding: 40px;
  box-shadow: 0 0 30px rgba(62, 171, 255, 0.3), inset 0 0 30px rgba(62, 171, 255, 0.1);
  backdrop-filter: blur(10px);
  min-width: 600px;
  max-width: 700px;
  max-height: 90vh;
  overflow-y: auto;
}

.register-form-container {
  width: 100%;
}

.form-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #fff;
  text-shadow: 0 0 10px rgba(62, 171, 255, 0.7);
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group.full-width {
  width: 100%;
}

.form-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid rgba(62, 171, 255, 0.3);
  border-radius: 8px;
  background: rgba(0, 35, 120, 0.3);
  color: #fff;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.form-input:focus {
  outline: none;
  border-color: rgba(62, 171, 255, 0.8);
  box-shadow: 0 0 15px rgba(62, 171, 255, 0.3);
  background: rgba(0, 35, 120, 0.5);
}

 .form-input:disabled {
   opacity: 0.5;
   cursor: not-allowed;
 }
 
   .unit-label {
    position: absolute;
    right: 15px;
    color: rgba(255, 255, 255, 0.6);
    font-size: 14px;
    pointer-events: none;
  }
  
  /* 下拉框样式 - 与项目整体风格保持一致 */
  select.form-input {
    appearance: none;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%233eabff' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 15px center;
    background-size: 16px;
    padding-right: 45px;
    cursor: pointer;
  }
  
  select.form-input:hover {
    border-color: rgba(62, 171, 255, 0.6);
    background-color: rgba(0, 35, 120, 0.4);
  }
  
  select.form-input:focus {
    border-color: rgba(62, 171, 255, 0.8);
    box-shadow: 0 0 15px rgba(62, 171, 255, 0.3);
    background-color: rgba(0, 35, 120, 0.5);
  }
  
  /* 下拉框选项样式 */
  select.form-input option {
    background-color: rgba(0, 35, 120, 0.9);
    color: #fff;
    padding: 12px 15px;
    border: none;
  }
  
  select.form-input option:hover {
    background-color: rgba(62, 171, 255, 0.3);
  }
  
  select.form-input option:checked {
    background-color: rgba(62, 171, 255, 0.5);
    color: #fff;
  }
 


.keywords-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.keywords-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.keyword-btn {
  padding: 10px 15px;
  border: 1px solid rgba(62, 171, 255, 0.3);
  border-radius: 6px;
  background: rgba(0, 35, 120, 0.3);
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
}

.keyword-btn:hover {
  background: rgba(62, 171, 255, 0.2);
  border-color: rgba(62, 171, 255, 0.6);
  color: #fff;
}

.keyword-btn.selected {
  background: linear-gradient(135deg, #3eabff, #205bcf);
  border-color: rgba(62, 171, 255, 0.8);
  color: #fff;
  box-shadow: 0 0 10px rgba(62, 171, 255, 0.4);
}

.register-btn {
  width: 100%;
  padding: 15px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #3eabff, #205bcf);
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
  box-shadow: 0 4px 15px rgba(62, 171, 255, 0.3);
}

.register-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #4bb8ff, #2968d9);
  box-shadow: 0 6px 20px rgba(62, 171, 255, 0.5);
  transform: translateY(-2px);
}

.register-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  background: rgba(255, 107, 107, 0.2);
  border: 1px solid rgba(255, 107, 107, 0.5);
  border-radius: 6px;
  padding: 12px;
  margin-top: 15px;
  color: #ff6b6b;
  text-align: center;
  font-size: 14px;
}

.back-to-login {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(62, 171, 255, 0.2);
}

.back-to-login span {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

.login-link {
  color: #3eabff;
  text-decoration: none;
  margin-left: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.3s ease;
}

.login-link:hover {
  color: #4bb8ff;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    margin: 20px;
    padding: 30px 20px;
    min-width: auto;
    max-width: 100%;
  }
  
     .form-row {
     flex-direction: column;
     gap: 15px;
   }
   

  
  .keywords-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .form-title {
    font-size: 20px;
  }
}

/* 自定义滚动条样式 - 与项目主题风格匹配 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(0, 35, 120, 0.2);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, rgba(62, 171, 255, 0.6), rgba(32, 91, 207, 0.8));
  border-radius: 4px;
  border: 1px solid rgba(62, 171, 255, 0.3);
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, rgba(62, 171, 255, 0.8), rgba(32, 91, 207, 1));
}

::-webkit-scrollbar-corner {
  background: rgba(0, 35, 120, 0.2);
}

/* Firefox 滚动条样式 */
* {
  scrollbar-width: thin;
  scrollbar-color: rgba(62, 171, 255, 0.6) rgba(0, 35, 120, 0.2);
}
</style>
